package com.sunwayworld.basemodule.business.batch.validators;

import com.sunwayworld.basemodule.business.batch.bean.LimsBatchBean;
import com.sunwayworld.basemodule.business.batch.service.LimsBatchSampleService;
import com.sunwayworld.basemodule.samplemanage.sample.bean.LimsSampleBean;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsBatchSubmitValidator implements DataValidator {

    @Autowired
    private LimsBatchSampleService sampleService;

    @Override
    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        boolean result = true;
        List<LimsBatchBean> testList = wrapper.parse(LimsBatchBean.class);
        List<Long> idList = testList.stream().map(LimsBatchBean::getId).collect(Collectors.toList());

        MapperParameter parameter = new MapperParameter();
        parameter.setFilter(SearchFilter.instance().match("batchId", idList).filter(MatchPattern.OR));
        List<LimsSampleBean> sampleBeans = sampleService.selectBatchSample(parameter);
        for (Long id : idList) {
            Optional<LimsSampleBean> optional = sampleBeans.stream().filter(s ->
                    s.getExt$Item("batchId").equals(id.toString())).findAny();
            if (!optional.isPresent()) {
                this.addConstraintViolation(I18nHelper.getMessage("BATCH.SUBBMIT.CHECK_SAMPLE_NOTEMPTY"));
                result = false;
            }
        }
        return result;
    }
}
